﻿var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var signCode = "slel3@lsl334xx,deka";
var Cio = require('socket.io-client');
var log = require("./../util/loginfo").getInstand;
var redis_dao = require("./dao/redis_dao");
var gameInfo = require('./class/game').getInstand;
var gameConfig = require('./config/gameConfig');

var Csocket = Cio('http://localhost:13000');


Csocket.on('disconnect', function (data) {
    log.info("登录服务器被断开")
});

Csocket.on('connected', function (msg) {
    log.info("与登录服务器进行连接......");
    var info = {serverName: "百人场_1021_抢庄百家乐", serverId: gameConfig.serverId, signCode: "slel3@lsl334xx,deka"};
    Csocket.emit('GameServerConnect', info)
});

Csocket.on('GameServerConnectResult', function (msg) {
    if (msg.resultCode) {
        log.info("连接成功");
    }
});


Csocket.on('LoginGameResult', function (msg) {
    if (!msg) {
        return;
    }
    log.info(".登录百人场_1021_抢庄百家乐服务器回应" + msg);
    if (msg.ResultCode) {
        gameInfo.updateUser(msg.userInfo);
    } else {
        gameInfo.deleteUserById(msg.userid, msg.msg);
    }

});

Csocket.on('addgold', function (msg) {
    if (!msg) {
        return;
    }
    //log.info(msg);
    var result = gameInfo.addgold(msg.userid, msg.addgold);
    Csocket.emit('addgoldResult', {Result: result});

    //当前用户桌子广播
    var User = gameInfo.getUser(msg.userid);
    if (User) {
        var tablestring = "table" + User.getTable();
        io.sockets.in(tablestring).emit('userGoldUpdate', {userId: msg.userid, updateSocre: User.getScore()});
    }
});

Csocket.on('getgold', function (msg) {
    if (!msg) {
        return;
    }

    //log.info(msg);
    var score = gameInfo.getPlayerScore(msg.userid);
    Csocket.emit('getgoldResult', {Result: 1, score: score});

});

Csocket.on('disconnectUser', function (msg) {
	//log.info("disconnectUser" + msg.userId);
	var list = gameInfo.getOnlinePlayer();
	if (list[msg.userId]) {
		// kicked, ZZZ-20230509
		list[msg.userId]._socket.emit(msg.sysCommand, msg);
		list[msg.userId]._socket.disconnect();
	} else {
		log.info("用户不存在");
		var result = { ResultCode: 0, userId: msg.userId };
		Csocket.emit("userDisconnect", result);
	}
});


Csocket.on('applyMatchResult', function (_info) {
    //log.info(_info);
    gameInfo.addRankUserList(_info);
    //gameInfo.fishShoot(socket,fishShootInfo);
});


Csocket.on('Setmaintain', function () {
    log.info("Setmaintain");
    gameInfo.Setmaintain();
});


gameInfo.setIo(io, Csocket);

io.on('connection', function (socket) {

    //log.info(socket + 'connected');
    socket.emit('connected', 'connect game server');


    //客户登录游戏
    socket.on('LoginGame', function (GameInfo) {
        try {
            var data = JSON.parse(GameInfo);
            GameInfo = data;
        } catch (e) {
            log.warn('LoginGame-json');
        }

        //是不是维护模式
        if (gameInfo.isMaintain()) {
            log.info("维护模式,禁止登录!");
            socket.emit("maintain", {ResultCode: 1, msg: true});
            return;
        }

        //log.info("test1.进入房间")
        //log.info(GameInfo)
        if (!GameInfo) {
            log.info("登录游戏,参数不正确!");
            return;
        }

        if (GameInfo.sign) {

            if (!gameInfo.getUser(GameInfo.userid)) {
                gameInfo.addUser(GameInfo, socket);
                var msg = {
                    userid: GameInfo.userid,
                    sign: GameInfo.sign,
                    gameId: gameInfo.serverId,
                    serverSign: signCode,
                    serverId: gameConfig.serverId
                };
                Csocket.emit('LoginGame', msg);
                //log.info("test4.发送新用户登录完成,让登录服务器删除用户")
            } else {
                log.info("用户已经在服务器了，无需重复登录");
            }
        }

    });

    //然后再登录房间
    socket.on('LoginRoom', function (RoomInfo) {
        try {
            var data = JSON.parse(RoomInfo);
            RoomInfo = data;
        } catch (e) {
            log.warn('LoginRoom-json');
        }
        //如果没有房间概念，就默认为1
        //这还应该检测是否进入了游戏，如果没有需要先进入
        //log.info("进入房间")
        gameInfo.LoginRoom(socket.userId, RoomInfo.roomid, socket)
    });


    //离开房间
    socket.on('LogoutRoom', function () {
        gameInfo.LogoutRoom(socket);
    });


    //登录游戏获取免费游戏次数
    socket.on('LoginfreeCount', function () {
        gameInfo.LoginfreeCount(socket.userId, socket);
    });


    //下注
    socket.on('lottery', function (lottery) {
        log.info("下注");
        try {
            var data = JSON.parse(lottery);
            lottery = data;
        } catch (e) {
            //log.warn('lottery-json');
        }
        if (socket.userId === gameInfo.zhuangUser) {
            log.info("庄不能下注");
            socket.emit('lotteryResult', {ResultCode: -1});
            return;
        }
        var result = gameInfo.lottery(socket.userId, lottery);
        if (result.code < 1) {
            socket.emit('lotteryResult', {ResultCode: result.code});
        } else {
            io.sockets.emit('lotteryResult', {ResultCode: result.code, bet_dict: result.bet_dict})
        }

    });

    //抢庄
    socket.on('upZhuang', function (info) {
        try {
            let data = JSON.parse(info);
            info = data;
        } catch (e) {
            log.warn('lottery-json');
        }
        if (!socket.userId) {
            log.info("no userId");
            socket.emit('upZhuangResult', {ResultCode: -1});
            return;
        }
        if (!gameInfo.userList[socket.userId]) {
            log.info("no userList" + socket.userId);
            socket.emit('upZhuangResult', {ResultCode: -1});
            return;
        }
        
        // if (gameInfo.zhuangList.length >= 20) {
        //     log.info("上庄人太多，无法上庄");
        //     socket.emit('upZhuangResult', {ResultCode: -1});
        //     return;
        // }

        var userscore = gameInfo.userList[socket.userId].getScore();
        if (userscore < info.coin) {
            log.info("money not enough user " + socket.userId);
            socket.emit('upZhuangResult', {ResultCode: -1});
            return;
        }

        let find = false;
        for (let i = 0; i < gameInfo.zhuangList.length; i++) {
            find = gameInfo.zhuangList[i].userId === socket.userId;
            if (find) {
                break;
            }
        }
        if (!find) {
            let newBanker = {
                userId: socket.userId,
                nickname: gameInfo.userList[socket.userId]._nickname,
                coin: info.coin
            };
            gameInfo.zhuangList.push(newBanker);
            io.sockets.emit('upZhuangResult', {ResultCode: 1, zhuangList: gameInfo.zhuangList});
        } else {
            socket.emit('upZhuangResult', {ResultCode: -1});
        }

    });
    //下庄
    socket.on('downZhuang', function () {
        if (!socket.userId) {
            log.info("没有用户id");
            socket.emit('downZhuangResult', {ResultCode: -1});
            return;
        }
        if (!gameInfo.userList[socket.userId]) {
            log.info("没有userList", socket.userId);
            socket.emit('downZhuangResult', {ResultCode: -1});
            return;
        }

        let find = false;
        for (let i = 0; i < gameInfo.zhuangList.length; i++) {
            find = gameInfo.zhuangList[i].userId === socket.userId;
            if (find) {
                gameInfo.zhuangList.splice(i, 1);
                break;
            }
        }
        if (find) {
            io.sockets.emit('downZhuangResult', {ResultCode: 1, zhuangList: gameInfo.zhuangList});
        } else {
            socket.emit('downZhuangResult', {ResultCode: -1});
        }

    });

    //获取游戏状态
    socket.on('getGameType', function (lottery) {
        log.info("获取游戏状态");
        redis_dao.get_bet_list().then(res => {
            var redis_dict = res;
            socket.emit('getGameTypeResult', {
                game_type: gameInfo.game_type,
                bet_time: gameInfo.bet_time,
                bet_list: redis_dict,
                zhuangList: gameInfo.zhuangList
            });

        }).catch(e => {

        })

    });

    //获取在线玩家列表
    socket.on('getOnline', function () {
        if (!socket.userId) {
            return;
        }
        log.info("获取在线玩家列表");
        gameInfo.getPlayer_online(socket);

    });

    //获取排行榜和神算子
    socket.on('getGameRankingList', function (lottery) {
        log.info("获取排行榜和神算子");
        socket.emit('getGameRankingListResult', {
            ranking_list: gameInfo.bet_pai_hang_list,
            shen_suan_zi: gameInfo.shen_suan_zi,
        });


    });

    //获取历史游戏记录
    socket.on('getGameRecordList', function (lottery) {
        log.info("获取历史记录");
        socket.emit('getGameRecordListResult', {
            game_record_list: gameInfo.game_record_list,
        });


    });


    //离线操作
    socket.on('disconnect', function () {
        if (!socket.userId) {
            return;
        }
        //通知登录服务器，已经下线存储游戏数据
        //log.info(socket.userId)
        var userInfo = gameInfo.getUser(socket.userId);
        if (userInfo) {
            if (userInfo.Islogin()) {
                gameInfo.deleteUser(socket);
                var result = {
                    ResultCode: 1,
                    userId: userInfo._userId,
                    userScore: userInfo._score,
                    gameId: gameConfig.serverId,
                    nolog: true
                };
                Csocket.emit("userDisconnect", result);
                //断线存储相应数据(在新的数据库里存储,消耗子弹与收获金币)
                socket.userId = null;
            } else {
                userInfo._isLeave = true;
                log.warn('未更新用户数据离开');
            }
        } else {
            log.info("用户未登录离开!")
        }
    })


});


app.set('port', process.env.PORT || gameConfig.port);

var server = http.listen(app.get('port'), function () {
    log.info('start at port:' + server.address().port);
});


log.info("百人场_1021_抢庄百家乐服务器启动");

